import os
import random
from PIL import Image, ImageDraw, ImageFont


def generate_logo(
    name, output_dir="logos", size=(100, 100), bg_color=None, text_color="#A9A9A9"
):
    """
    为给定名称生成一个简单的 logo

    参数:
        name: 名称字符串
        output_dir: 输出目录
        size: logo 尺寸，默认 64x64
        bg_color: 背景颜色，默认从预设颜色中随机选择
        text_color: 文字颜色，默认为淡灰色 #A9A9A9
    """
    # 确保输出目录存在
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 背景颜色列表
    bg_colors = [
        "#F8F8FF",  # 幽灵白
        "#F6F7F9",  # 淡灰蓝
        "#FFFAF0",  # 花卉白
        "#F0FFFF",  # 天蓝色
        "#FFF0F5",  # 淡紫红
        "#FFFFE0",  # 浅黄色
        "#F0FFF0",  # 蜜瓜绿
        "#E0FFFF",  # 浅青色
        "#FFDCB9",  # 浅橙色
        "#D1E9E9",  # 浅青色
        "#EBD6D6",
        "#EBD3E8",
    ]

    # 如果没有指定背景颜色，则随机选择一个
    if bg_color is None:
        bg_color = random.choice(bg_colors)

    # 创建一个新的白色背景图像
    img = Image.new("RGB", size, color=bg_color)
    draw = ImageDraw.Draw(img)

    # 随机决定是使用首字母还是前两个字母
    if not name:
        text = "?"
    elif len(name) == 1:
        # 只有一个字符时使用该字符
        text = name[0].upper()
    elif name[0].isdigit():
        # 如果第一个字符是数字，则取前两个字符
        if len(name) >= 2:
            text = name[0] + name[1]
        else:
            text = name[0]
    elif random.choice([True, False]):
        # 获取首字母并转为大写
        text = name[0].upper()
    else:
        # 获取前两个字母，第一个大写，第二个小写
        text = name[0].upper() + name[1].lower()

    # 尝试加载字体，如果失败则使用默认字体
    try:
        # 尝试使用一个常见的字体，根据系统可能需要调整
        font = ImageFont.truetype("arial.ttf", size[0] // 2)
    except IOError:
        # 如果找不到指定字体，使用默认字体
        font = ImageFont.load_default()

    # 使用新的 API 计算文本大小
    bbox = draw.textbbox((0, 0), text, font=font)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]

    # 调整垂直位置，考虑字体的基线偏移
    ascent, descent = font.getmetrics()
    position = (
        (size[0] - text_width) // 2,  # 水平居中
        (size[1] - text_height) // 2 - (ascent - text_height) // 2,  # 垂直居中
    )

    # 绘制文本
    draw.text(position, text, fill=text_color, font=font)

    # 保存图像
    output_path = os.path.join(output_dir, f"{name}.png")
    img.save(output_path)

    return output_path


def generate_logos_for_list(nameList):
    """
    为名称列表中的每个名称生成 logo

    参数:
        nameList: 名称字符串列表

    返回:
        生成的 logo 文件路径列表
    """
    logo_paths = []
    for name in nameList:
        if name and isinstance(name, str):
            path = generate_logo(name, bg_color="#F6F7F9")
            logo_paths.append(path)
            print(f"已为 {name} 生成 logo: {path}")

    return logo_paths


if __name__ == "__main__":
    # gitcode landscape 需要替换的软件 name
    nameList = [
        "lama",
        "Drawflow",
        "3D-Machine-Learning",
        "awesome-blender",
        "pbrt-v4",
        "dust3d",
        "models",
        "Online3DViewer",
        "3D-printed-mirror-array",
        "Autodesk-Fusion-360-for-Linux",
        "nunuStudio",
        "antimony",
        "3DUnetCNN",
        "sketch-isometric",
        "KiKit",
        "awesome-3d-printing",
        "Prusa3",
        "AM",
        "simsim",
        "masa",
        "machine-learning-and-simulation",
        "fem-layout",
        "simanneal",
        "vorms",
        "Compute-Shaders-Fluid-Dynamic-",
        "gyro",
        "machine-learning-asset-management",
        "PLMCodeTemplate",
        "jshERP",
        "Asp.Net-Core-Inventory-Order-Management-System",
        "erpsaas",
        "camaro",
        "PL-VIO",
        "awesome-devops",
        "SMRY",
        "org.openwms",
        "rtl_433",
        "ofelia",
        "systeminformation",
        "pg-boss",
        "home-assistant-config",
        "ied",
        "zeu",
        "EDR-Telemetry",
        "Phant0m",
        "ControlPlane",
        "Process-Dump",
        "sysz",
        "dashboard",
        "qlcplus",
        "Neuron",
        "indicator",
        "awesome-product-management",
        "SCRecorder",
        "ClientServerProject",
        "PythonRobotics",
        "johnny-five",
        "Dummy-Robot",
        "aisuite",
        "AeroSpace",
        "awesome-c",
        "eul",
        "ansible-for-devops",
        "RobustVideoMatting",
        "MVision",
        "ElectronBot",
        "jetson-inference",
        "AI4Animation",
        "machinery",
        "linux-network-performance-parameters",
        "EdgeDeflector",
        "reconnecting-websocket",
        "edge-connect",
        "sdrangel",
        "Awesome-Edge-Detection-Papers",
        "LFFD-A-Light-and-Fast-Face-Detector-for-Edge-Devices",
        "EdgeSAM",
        "k8s-on-raspbian",
        "openai-edge-tts",
        "edge-sql",
        "mylg",
        "awesome-network-embedding",
        "awesome-canbus",
        "mirotalksfu",
        "arduino-LoRa",
        "RTNetworking",
        "Connectivity",
        "PcbDraw",
        "zigbee2mqtt",
        "awesome-mlops",
        "industry-machine-learning",
        "Jenkins-Zero-To-Hero",
        "sketch-measure",
        "meshoptimizer",
        "PlotJuggler",
        "ta",
        "DeepLearnToolbox",
        "awesome-ci",
        "windows-build-tools",
        "easy_profiler",
        "creep",
        "koila",
        "FastScriptReload",
        "engineercms",
        "TableTool",
        "devtools-terminal",
        "cz-git",
        "logger",
        "node-drawille",
        "altium-library",
        "SavvyCAN",
        "EasyModbusTCP.NET",
        "arpl",
        "OctoPrint_OctoPrint",
        "Network-segmentation-cheat-sheet",
        "battery",
        "powerline-go",
        "GoldenCheetah",
        "BYD-Battery-Emulator-For-Gen24",
        "powertop",
        "battery-state-card",
        "php-code-coverage",
        "loadtest",
        "awesome-regression-testing",
        "UI-Testing-Cheat-Sheet",
        "awesome-testing",
        "awesome-quality-assurance-roadmap",
        "circuitjs1",
        "Vitals",
        "TestDrive",
        "pytest-sugar",
        "testing-workshop",
        "gotest",
        "pytest-benchmark",
        "unit-testing-tips",
        "Monitorix",
        "doctrine-test-bundle",
        "testing-react-apps",
        "laravel-test-factory-helper",
        "PTI",
        "myzap",
        "pytest-testmon",
        "software-testing-interview-question",
        "NetworkEye",
        "codelite",
        "Qt-Advanced-Docking-System",
        "constanline_XQuickEnergy",
        "pansong291_XQuickEnergy",
        "ScopeSentry",
    ]
    generate_logos_for_list(nameList)
